//app.js
const mta = require('/mta_sdk/mta_analysis.js');
App({
  onLaunch: function (opt) {
    this.globalData.userData=wx.getStorageSync('userData') || {};
    this.globalData.scene = opt.scene;
    this.checkSession();
    mta.App.init({
      "appID":"500640168",
      "eventID":"500640169",
      "statPullDownFresh":true,
      "statShareApp":true,
      "statReachBottom":true
  });
  },
  onShow(){},
  globalData: {
    userInfo: null,
    userData:{},
    domain:"https://api.gzyygame.com/Heart/",
    appid:'wx844b1ab5e3084d54',
    scene:'',
    version:1
  },
  ajax(params){
    /*
      @param:
      url:请求地址
      loading:是否显示加载中
      data:携带数据
      method:请求方式,默认POST
      loadTip:加载标题
      @用法：app.ajax({...}).then(res=>{console.log("成功")}).catch(err){console.log("err")}
    */
    return new Promise((resolve, reject) => {
       //默认一些参数
      let me = this;
      params.data=params.data?params.data:{};
      params.data.appid = me.globalData.appid;
      params.data.uid = me.globalData.userData.uid || '';
      params.data.scene = me.globalData.scene;
      params.data.version = me.globalData.version;
      if (params.loading) {
        
        wx.showLoading({
          title: params.loadTip || '玩命加载中...',
        });
      }
      wx.request({
        url: me.globalData.domain + params.url,
        method: params.method || 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': 'PHPSESSID=' + me.globalData.session_id
        },
        data: params.data,
        success: res => {
          resolve(res.data);
          if (params.loading) {
            wx.hideLoading();
          }
        },
        fail:err=>{
          reject(err);
          wx.showToast({
            title: '网络错误~',
            icon:'none'
          });
          console.log(err);
        },
        complete:com=>{
          
        }
      })
    })
  },
   //获取用户数据
   userLogin: function (info,callback) {
    if (!info) {
      wx.showModal({
        title: '提示',
        content: '获取用户信息失败！',
        complete:res=>{
          if(res.confirm){
            this.clearSto();
          }
        }
      });
      return false;
    }
    if(this.globalData.userData.openid){
      callback();
      return false;
    }
    wx.login({
      success: a => {
        this.wxLogin(a.code, info, callback);
      },
      fail: b => {console.log('login fail') },
    });
  },
  //获取openid
  wxLogin: function (code, info, callback) {
    
    this.ajax({
      url: 'User/login',
      data: {
        code: code,
        info: JSON.stringify(info)
      },
      method: 'POST',
      loading: true,
      loadTip: '登录中...'
    }).then(res => {
        console.log(res);
        if (res.code==200){
          var udata={
            openid:res.data.openid,
            session_id:res.data.session_id,
            uid:res.data.uid,
          }
          this.globalData.userData=udata;
          wx.setStorageSync('userData', udata);
          wx.setStorageSync('userInfo', info);
          callback(res.data);
          console.log("请求成功")
        }
        else{
          wx.showToast({
            title: '获取用户信息失败',
            icon:'none'
          })
        }
      
    }).catch(err => {
      //console.log(err);
    });
  },
  //检测登录过期
  checkSession(){
    wx.checkSession({
      success: res => {
        console.log("有效");
        if (this.globalData.uid == '') {
          this.clearSto();
        }
      },
      fail: res => {
        //Session失效了就清除缓存
        console.log("失效")
        this.clearSto();
      }
    });
  },
  //清除缓存
  clearSto() {
    wx.removeStorageSync("userData");
    wx.removeStorageSync("userInfo");
  },
  //发送模板消息
  sendForm: function (e) {
    let me = this;
    me.ajax({
      url: "Index/send",
      data: {
        "touser": me.globalData.userData.openid,
        "template_id": '',
        "page": "/pages/index/index",
        "form_id": e.detail.formId,
        "form_type": 1
      }
    }).then(res => {
      if(res.code==200){
        console.log("发送模板成功")
      }
      else{
        console.log("send fail")
      }
    }).catch(err=>{
      console.log("发送err",err);
    })
    
  },
  toast(t){
    wx.showToast({
      title:t,
      icon:'none'
    })
  },
  //跳转小程序
  openApp(id, path) {
    wx.navigateToMiniProgram({
      appId: id,
      path: path,
      extraData: {},
      success(res) {
        console.log("openMini success")
      },
      fail: res => {
        console.log(res)
      }
    })
  },
})